package com.yunkeji.config.keymonitor.task;

import com.yunkeji.api.user.mapper.ApiAppUserMapper;
import com.yunkeji.common.constant.CacheConstants;
import com.yunkeji.common.enums.app.AppUserStatus;
import com.yunkeji.common.helper.LoginHelper;
import com.yunkeji.config.keymonitor.config.RedisListenerFactory;
import com.yunkeji.config.keymonitor.config.RedisListenerStrategy;
import com.yunkeji.dao.domain.AppUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 老张
 * @version V1.0
 * @description 账号删除
 * @date 2021/11/15 14:10
 * @update 2021/11/15 14:10
 */
@Component
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class DelAccount implements InitializingBean, RedisListenerStrategy {

    private final ApiAppUserMapper apiAppUserMapper;

    @Override
    public void afterPropertiesSet() throws Exception {
        RedisListenerFactory.put(CacheConstants.DEL_ACCOUNT, this);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void execute(String keyInfo) {
        log.info("账号删除:{}", keyInfo);
        AppUser appUser =
                apiAppUserMapper.selectById(keyInfo.replace(CacheConstants.DEL_ACCOUNT, ""));
        if (appUser != null && !appUser.getStatus().equals(AppUserStatus.永久删除.getCode())) {
            appUser.setStatus(AppUserStatus.永久删除.getCode());
            apiAppUserMapper.updateById(
                    new AppUser().setStatus(AppUserStatus.永久删除.getCode()).setId(appUser.getId()));
            LoginHelper.removeLoginCacheInfo(appUser.getId());
        }
    }
}
